<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${dataId ? '编辑' : '新增'}-前纺单价`"
		width="520px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="confirmBtnLoading"
		append-to-body
		:permission-prefix="permissionPrefix"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="110px" :show-message="false">
			<el-row>
				<el-col :span="22">
					<el-form-item class="margin-bottom-10" label="工序" prop="processCode">
						<jk-select v-model="ruleForm.processCode" size="medium" value-key-name="code" :option-list="processList" class="width-100-percent" placeholder="工序" @change="onProcessChange"></jk-select>
					</el-form-item>
				</el-col>
				<el-col :span="22">
					<el-form-item class="margin-bottom-10" :label="ruleForm.processCode.toUpperCase() === 'CS' ? '单价(元/公斤)' : '单价(元/米)'" prop="price">
						<div class="flex-start-center">
							<jk-number-input v-model="ruleForm.price" placeholder="元" size="medium"></jk-number-input>
							<span style="white-space: nowrap;margin: 0 4px;"> / </span>
							<jk-number-input v-model="ruleForm.unit" :placeholder="ruleForm.processCode.toUpperCase() === 'CS' ? '公斤' : '米'" size="medium"></jk-number-input>
						</div>
					</el-form-item>
				</el-col>
				<!--<el-alert v-if="ruleForm.processCode && ruleForm.processCode.toUpperCase() === 'SM'" title="此类机台的看台人员工资固定为0，同时根据米换算公斤" class="margin-bottom-10 margin-top-10" :closable="false" show-icon size="mini" type="warning"></el-alert>-->
				<el-col v-if="ruleForm.processCode && ruleForm.processCode.toUpperCase() === 'SM'" :span="22">
					<el-form-item class="margin-bottom-10" label="特殊机台">
						<div class="flex-start-center-wrap">
							<el-tag
								v-for="(machineItem, machineIndex) in ruleForm.machineItemList"
								:key="machineIndex"
								class="item-gap"
								style="margin-bottom: 4px;"
								size="large"
							>{{ machineItem.machineCode }}</el-tag>
							<el-tag type="info" class="el-icon-plus pointer" size="large" @click="selectMachineDialogState = true"></el-tag>
						</div>
					</el-form-item>
				</el-col>
				<el-col :span="22">
					<el-form-item class="margin-bottom-10" label="单位换算" prop="meters1">
						<div class="flex-start-center">
							<jk-number-input v-model="ruleForm.meters" placeholder="单位换算" size="medium" class="item-gap"></jk-number-input>
							<span style="white-space: nowrap;font-size: 12px;color: #515a6e;">米换算公斤</span>
						</div>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<select-machine-dialog
			:default-select-rows="ruleForm.machineItemList"
			check-key-name="machineId"
			:dialog-state="selectMachineDialogState"
			@on-confirm="onConfirmBtnOfSelectMachineDialog"
			@on-visible-change="onVisibleChangeOfSelectMachineDialog"
		></select-machine-dialog>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import { spinFrontPriceCreate, spinFrontPriceUpdate, spinFrontPriceGet } from '../../../api/material/frontPriceUnitConversion';
    import selectMachineDialog from '../../schedule/empMachine/components/checkbox-machine-dialog';
    export default {
        props: {
            // 页面权限的前缀
            permissionPrefix: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        components: { selectMachineDialog },
        mixins: [calHeight],
        data() {
            return {
                selectMachineDialogState: false,
                processList: [],
                showDialog: false,
                showLoading: true,
                confirmBtnLoading: false,
                saveDialogState: false,
                ruleForm: {
                    'price': null,
                    'unit': null,
                    'meters': null,
                    'processCode': '',
                    'machineItemList': []
                },
                rules: {
                    processCode: [{ required: true, trigger: 'change' }],
                    price: [{ required: true, trigger: 'change' }],
                    meters: [{ required: true, trigger: 'change' }]
                }
            };
        },
        methods: {
            onProcessChange() {
                this.$set(this.ruleForm, 'machineItemList', []);
            },
            onConfirmBtnOfSelectMachineDialog(e) {
                if (e.length) {
                    this.selectMachineDialogState = false;
                    e.forEach(x => {
                        this.ruleForm.machineItemList.push({
                            machineId: x.id,
                            machineCode: x.code,
                            machineName: x.name
                        });
                    });
                }
            },
            onVisibleChangeOfSelectMachineDialog(e) {
                this.selectMachineDialogState = e;
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                const processItem = this.processList.find(x => x.code === params.processCode) || {};
                params.processCode = processItem.code;
                params.processName = processItem.name;
                return params;
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        if (this.ruleForm.unit) {
                            this.createAndUpdateRequest();
                        } else {
                            this.$tipsBar(this, 'custom', 'warning', '单位不能为空!');
                        }
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            createAndUpdateRequest() {
                this.confirmBtnLoading = true;
                // 新增
                if (!this.dataId) {
                    this.ruleForm.id = null;
                    spinFrontPriceCreate(this.getParamData()).then(res => {
                        this.confirmBtnLoading = false;
                        if (res.data.status === 200) {
                            this.$tipsBar(this, 'save');
                            this.$emit('on-finish');
                        }
                    });
                    return;
                }
                // 编辑
                spinFrontPriceUpdate(this.getParamData()).then(res => {
                    this.confirmBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return spinFrontPriceGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        resData.machineItemList = resData.machineItemList || [];
                        this.ruleForm = resData;
                    }
                });
            },
            async getDependentData() {
                this.processList = this.$store.state.user.userProcess.processList;
                this.showLoading = true;
                if (this.dataId) await this.getDetailRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
